#include <51func.h>
int main(int argc, char *argv[])
{
    // ./2_azhen 192.168.118.128 1234
    ARGS_CHECK(argc,3);
    // socket
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(argv[2]));
    serverAddr.sin_addr.s_addr = inet_addr(argv[1]);
    // setsockopt
    int arg = 1; // REUSEADDR的参数值为真
    int ret = setsockopt(sockfd,SOL_SOCKET,
                         SO_REUSEADDR,&arg,sizeof(arg));
    ERROR_CHECK(ret,-1,"setsockopt");
    // bind
    ret = bind(sockfd,(struct sockaddr *)&serverAddr,sizeof(serverAddr));
    ERROR_CHECK(ret,-1,"bind");
    // listen
    listen(sockfd,10);
    // accept
    struct sockaddr_in clientAddr;
    socklen_t clientAddrLength = sizeof(clientAddr); //必须赋初值
    int netfd = accept(sockfd,(struct sockaddr *)&clientAddr,&clientAddrLength);
    printf("client ip = %s, port = %d\n",inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
    char buf[4096];
    int epfd = epoll_create(1); //创建epoll文件对象
    // 增加监听
    struct epoll_event event;
    event.events = EPOLLIN;//读事件
    event.data.fd = STDIN_FILENO; // 该文件描述符就绪，会告知调用者fd为STDIN_FILENO
    epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&event);
    event.events = EPOLLIN|EPOLLET;//EPOLLET 边缘触发
    event.data.fd = netfd; // 该文件描述符就绪，会告知调用者fd为netfd
    epoll_ctl(epfd,EPOLL_CTL_ADD,netfd,&event);
    while(1){
        // 为就绪集合申请内存
        struct epoll_event readyset[2];
        int readynum = epoll_wait(epfd,readyset,2,-1);
        printf("epoll_wait ready!\n");
        for(int i = 0; i < readynum; ++i){
            if(readyset[i].data.fd == STDIN_FILENO){
                bzero(buf,sizeof(buf));
                ssize_t sret = read(STDIN_FILENO,buf,sizeof(buf));
                send(netfd,buf,strlen(buf),0);
            }
            else if(readyset[i].data.fd == netfd){
                bzero(buf,sizeof(buf));
                while(1){
                    ssize_t sret = recv(netfd,buf,2,MSG_DONTWAIT);
                    if(sret == -1 || sret == 0){
                        break;
                    }
                    printf("buf = %s\n", buf);
                }
            }
        }
    }
    return 0;
}

